package com.zrt.pad.commonui;

import java.util.ArrayList;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.zrt.pad.padpos.R;

public class CustomSwitch extends LinearLayout implements OnTouchListener  {

	private ImageView thumb;
	private boolean isOn;
	private int leftBorder;
	private int rightBorder;
	private int keyPoint;
	private static DisplayMetrics mDisplayMetrics = new DisplayMetrics(); 
	private int P_W;
	private int P_H;

	public CustomSwitch(Context context, AttributeSet attrs) {
		super(context, attrs);
	
		int W = getDisplayMetrics(context).widthPixels;
		int H = getDisplayMetrics(context).heightPixels;
		
		Log.e("TAG", "W" + W);
		Log.e("TAG", "H" + H);
		
		
		thumb = new ImageView(context);
		Resources r = context.getResources();
		Drawable thumbImg = r.getDrawable(R.drawable.set_switch_thumb);
		thumb.setImageDrawable(thumbImg);
		thumb.setScaleType(ScaleType.CENTER);
		// bg 176*31 左1 右1 上1 下2 带阴影
		// bg 174*28
		// thumb 103*38 左3 右5 上2 下4 带阴影
		// thumb 95*32
		leftBorder = -5;
		if (2048 == W && 1440 == H) {
			rightBorder = 174;		
			P_W = 188;
			P_H = 63;
		} else if(1280 == W && 752 == H || 800 == H) {
			rightBorder = 174 - 95 + 4;		 // 1280*800 分辨率 用：  174 - 95 + 4;
			P_W = 103;
			P_H = 38;
		} else {
			rightBorder = 174 - 95 + 4;	
			P_W = 103;
			P_H = 38;
		}
															 
		keyPoint = (int) ((rightBorder - leftBorder) / 2.0);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(P_W, P_H);    //1280*800 分辨率 用：  (103, 38);
		// 抛开阴影，对齐的话需要-2 -1 0 0
		// 加上阴影是-3 -1 0 0
		// 背景有个圆角透明，要盖住还需要-2
		// 32 - 28 = 4
		// 还需要再上移4/2=2像素
		params.setMargins(-5, -3, 0, 0);
		addView(thumb, params);
		isOn = false;
		setClipChildren(false);
		setClipToPadding(false);
		thumb.setClickable(false);
		setOnTouchListener(this);

	}

	private static DisplayMetrics getDisplayMetrics(Context context) {
//		Display mDisplay = getWindowManager().getDefaultDisplay();
//		int W = mDisplay.getWidth();
//		int H = mDisplay.getHeight();
		
		WindowManager windowMgr = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
		windowMgr.getDefaultDisplay().getMetrics(mDisplayMetrics);
		
		return mDisplayMetrics;
	}
	
	private void moveToRight() {
		ValueAnimator va = ValueAnimator.ofInt((int) thumb.getX(), rightBorder);

		va.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				int v = (Integer) animation.getAnimatedValue();
				thumb.setX(v);

			}
		});
		final int length = rightBorder - leftBorder;
		float offset = Math.abs(thumb.getX() - rightBorder);
		float percent = offset / length;
		va.setDuration((long) (300 * percent));
		va.start();
	}

	private void moveToLeft() {
		ValueAnimator va = ValueAnimator.ofInt((int) thumb.getX(), leftBorder);

		va.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				int v = (Integer) animation.getAnimatedValue();
				thumb.setX(v);

			}
		});
		final int length = rightBorder - leftBorder;
		float offset = Math.abs(thumb.getX() - leftBorder);
		float percent = offset / length;
		va.setDuration((long) (300 * percent));
		va.start();
	}

	public void setOn(boolean on, boolean animate) {
		if (isOn != on) {
			// 从on到off ←
			if (isOn) {
				if (animate) {
					moveToLeft();
				} else {
					thumb.setX(leftBorder);
				}
			} else {
				// 从off到on →
				if (animate) {
					moveToRight();
				} else {
					thumb.setX(rightBorder);
				}
			}
			isOn = on;
			for (OnValueChangedListener listener : vcListener) {
				listener.onValueChange(this, isOn);
			}
		}

	}
	
	public void setOn(boolean on){
		setOn(on, true);
	}

	private float preX;
	private float preTouchX;
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			preX = thumb.getX();
			preTouchX = event.getX();
		}
			break;
		case MotionEvent.ACTION_MOVE: {
			// 不能超出边界
			float x = thumb.getX();
			float moveX = event.getX() - preTouchX;
			preTouchX = event.getX();
			float destX = x + moveX;
			if (destX < leftBorder || destX > rightBorder) {
				return true;
			}
			thumb.setX(destX);
		}
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP: {
			// 移动距离超过1/2，则修改状态
			if (Math.abs(thumb.getX() - preX) > keyPoint) {
				if (thumb.getX() > keyPoint) {
					setOn(true);
				} else {
					setOn(false);
				}
			} else {
				// 如果按下和弹起的移动距离小于10像素，视为点击事件
				if (Math.abs(thumb.getX() - preX) < 10) {
					if (isOn) {
						setOn(false);
					} else {
						setOn(true);
					}
				} else {
					if (thumb.getX() > keyPoint) {
						moveToRight();
					} else {
						moveToLeft();
					}
				}
			}
		}
			break;
		default:
			break;
		}

		return true;
	}

	public interface OnValueChangedListener {
		public void onValueChange(CustomSwitch v, boolean isOn);
	}

	private ArrayList<OnValueChangedListener> vcListener = new ArrayList<CustomSwitch.OnValueChangedListener>();

	public void addOnValueChangedListener(OnValueChangedListener listener) {
		vcListener.add(listener);
	}
}